//
//  ZCHotTagsVC.m
//  zctx
//
//  Created by apple on 16/4/11.
//  Copyright © 2016年 sanliang. All rights reserved.
//

#import "ZCHotTagsVC.h"
#import "ZCTagsControl.h"
#import "ZCSearchVC.h"
#import "ZCSearchHeaderView.h"
#import "ZCSearchFmdb.h"
#import "ZCSearchTagsCell.h"
#import "ZCHotFootView.h"

#import "ZCsearchHistoryDataBase.h"

@interface ZCHotTagsVC ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate,ZCTagsControlDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZCTagsControl *tagsControl;  //标签
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIBarButtonItem *searchButton;

@property (nonatomic, strong) NSArray *biaoArray; //标签数组
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation ZCHotTagsVC


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCHotTagsVC"];
    [MTA trackPageViewBegin:@"ZCHotTagsVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    self.searchBar.text = @"";
    self.dataArray = [[ZCsearchHistoryDataBase shareDataBase]readLocalArray];
    [self.tableView reloadData];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCHotTagsVC"];
    [MTA trackPageViewEnd:@"ZCHotTagsVC"];
}

-(void)updateRequest{
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus >0) {
        self.bannerView.hidden = YES;
    }
//    [self requestMainList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initnavegation];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    NSLog(@"self.dataArray = %@",self.dataArray);
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.tableView.tableHeaderView = self.tagsControl;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchTagsCell" bundle:nil] forCellReuseIdentifier:@"tags"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self hotsearchRequest];
    });
    
}

#pragma mark 热门搜索标签请求
-(void)hotsearchRequest{
    [NetworkManager requestProductGetsearchKeywordsWithMid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        if ([[dictResponse objectForKey:@"content"] isKindOfClass:[NSArray class]]) {
            NSArray *array = (NSArray *)[dictResponse objectForKey:@"content"];

            self.biaoArray = [array copy];
            self.tagsControl.tagsArray = self.biaoArray;
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)ZCTagsControlSelectIndex:(NSInteger)index andWith:(NSString *)title{
    NSLog(@"index = %ld ,title = %@",index,title);
    
    ZCSearchVC *search = [[ZCSearchVC alloc]init];
    search.hidesBottomBarWhenPushed = YES;
    search.searchStr = title;
    
    UINavigationController *naloginvc = [[UINavigationController alloc]initWithRootViewController:search];
    naloginvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:naloginvc animated:YES completion:nil];
    
    [self addHistoryWithString:title];//增加数据
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataArray.count>=10) {
        return 10;
    }else{
        return self.dataArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"tags";
    ZCSearchTagsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell==nil) {
        cell = [[ZCSearchTagsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.num =(int)indexPath.row;
    if (indexPath.row>=0&&indexPath.row<self.dataArray.count) {
        cell.titleLable.text = self.dataArray[indexPath.row];
    }
    __weak ZCHotTagsVC *weakSelf = self;
    cell.delBlock = ^(int num){
        [weakSelf deleteHistoryWithIndex:num];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (self.dataArray.count>0) {
        ZCSearchHeaderView *headview = [[ZCSearchHeaderView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 35)];
        return headview;
    }else{
        return nil;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.dataArray.count>0) {
        return 35;
    }else{
        return 0.001;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.dataArray.count>0) {
        return 44;
    }else{
        return 0.001;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (self.dataArray.count>0) {
        ZCHotFootView *footer =[[ZCHotFootView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,44)];
        __weak ZCHotTagsVC *weakSelf = self;
        footer.hotBlock = ^(void){
            [weakSelf dismissLogin];
        };
        return footer;
    }else{
        return nil;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZCSearchVC *search = [[ZCSearchVC alloc]init];
    search.hidesBottomBarWhenPushed = YES;
    search.searchStr = self.dataArray[indexPath.row];
    
    UINavigationController *naloginvc = [[UINavigationController alloc]initWithRootViewController:search];
    naloginvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:naloginvc animated:YES completion:nil];
    
    [self addHistoryWithString:self.dataArray[indexPath.row]];//增加数据
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    UIView * spaceView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,5, 32)];
    UIBarButtonItem * barButtonItem_spaceView = [[UIBarButtonItem alloc] initWithCustomView:spaceView];
    self.navigationItem.leftBarButtonItems = @[barButtonItem_leftNavBar,barButtonItem_spaceView];
    
    self.navigationItem.rightBarButtonItems = @[self.searchButton,barButtonItem_spaceView];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-140, 30)];//allocate titleView
    UIColor *color =  self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.delegate = self;
    _searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH-140, 30);
    _searchBar.backgroundColor = color;
    _searchBar.layer.cornerRadius = 15;
    _searchBar.layer.masksToBounds = YES;
    _searchBar.clearsContextBeforeDrawing = YES;
    [_searchBar.layer setBorderWidth:8];
    [_searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];  //设置边框为白色
    _searchBar.placeholder = @"搜索产品 查看食品检测报告";
    [titleView addSubview:_searchBar];
    //Set to titleView
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = titleView;
}

//添加一条历史记录
- (void)addHistoryWithString:(NSString *)string{
    
    //先改变tableview的数据源
    if ([self.dataArray containsObject:string]) {
        [self.dataArray removeObject:string];
    }
    [self.dataArray insertObject:string atIndex:0];
    
    //存储新的数据源到本地，以保证下次打开程序有之前搜索的记录
    [[ZCsearchHistoryDataBase shareDataBase]writeLocalWithDataArray:self.dataArray];
}


//删除一条
- (void)deleteHistoryWithIndex:(NSInteger)index{
    
    if (index >=0&& index<self.dataArray.count) {
        
        [self.dataArray removeObjectAtIndex:index];
        [[ZCsearchHistoryDataBase shareDataBase]writeLocalWithDataArray:self.dataArray];
        [self.tableView reloadData];
    }
}

#pragma mark 清除所有搜索历史记录
-(void)deleteAllBtnClicks{

    if (self.dataArray.count>0) {
        [self.dataArray removeAllObjects];
        [[ZCsearchHistoryDataBase shareDataBase]writeLocalWithDataArray:self.dataArray];
        [self.tableView reloadData];
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self searchButtonClick];
}

#pragma mark - instance
- (UIBarButtonItem *)searchButton {
    if (!_searchButton) {
        _searchButton = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonClick)];
    }
    return _searchButton;
}
#pragma mark 搜索
- (void)searchButtonClick {
    [_searchBar resignFirstResponder];
    
    ZCSearchVC *search = [[ZCSearchVC alloc]init];
    search.hidesBottomBarWhenPushed = YES;
    search.searchStr = self.searchBar.text;
    
    UINavigationController *naloginvc = [[UINavigationController alloc]initWithRootViewController:search];
    naloginvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:naloginvc animated:YES completion:nil];
    
    if (![NSString isNull:self.searchBar.text]) {
        [self addHistoryWithString:self.searchBar.text];
    }
}

-(void)dismissLogin{
    if (DEVICE_SYSTEM_VERSION) {
        [self showAlert];;
    }else{
        [self showAlertold];
    }
}

-(void)showAlert{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"要清除搜索历史吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 回调在block里面
        // to do..
        NSLog(@"sd");
    }];
    UIAlertAction *actionDelete = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // to do..
        [self deleteAllBtnClicks];
    }];
    [alert addAction:action];
    [alert addAction:actionDelete];
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)showAlertold{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"要清除搜索历史吗？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex ==1) {
        [self deleteAllBtnClicks];
    }
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
        _tableView.separatorColor = RGB(236, 237, 238);
    }
    return _tableView;
}
-(ZCTagsControl *)tagsControl{
    if (!_tagsControl) {
        self.tagsControl = [[ZCTagsControl alloc]initWithFrame:CGRectZero];
        self.tagsControl.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
        self.tagsControl.delegate = self;
    }
    return _tagsControl;
}

-(void)backButtonPressed{
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}


-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
